package cn.com.haopy.yue.ai.wx.web;


import cn.com.haopy.yue.ai.core.component.CacheComponent;
import cn.com.haopy.yue.ai.core.config.ChatApiProperties;
import cn.com.haopy.yue.ai.core.config.storage.StorageService;
import cn.com.haopy.yue.ai.core.utils.RedisCachePreFix;
import cn.com.haopy.yue.ai.core.utils.ResponseUtil;
import cn.com.haopy.yue.ai.db.entity.arisk.HOSStorage;
import cn.com.haopy.yue.ai.db.entity.arisk.HOSUser;
import cn.com.haopy.yue.ai.wx.dto.AIPdfResDto;
import cn.com.haopy.yue.ai.wx.service.*;
import cn.com.haopy.yue.ai.wx.web.base.BaseWxController;
import com.alibaba.fastjson.JSONObject;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.net.HttpURLConnection;
import java.net.URI;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

/**
 * 登录
 */
@RestController
@RequestMapping("/haopyYueAi/test")
@RequiredArgsConstructor
@Slf4j
@Api(tags = "测试")
public class WxTestController extends BaseWxController {
    @Autowired
    private CacheComponent cacheComponent;

    @Autowired
    private PdfAiApiService pdfAiApiService;
    @Autowired
    private WxPaperPdfService wxPaperPdfService;

    @Autowired
    private StorageService storageService;

    @Autowired
    private WxPapersPresIllnessService wxPapersPresIllnessService;


    @Autowired
    private ChatAiApiService chatAiApiService;

    @Autowired
    private ChatApiProperties chatApiProperties;

    @Autowired
    private WxPapersDrugsService wxPapersDrugsService;

    @Autowired
    private PaperIllnessToAISyncService paperIllnessToAISyncService;

    @PostMapping("/testInfo")
    @ApiOperation(value = "微信登录测试")
    public Object testInfo(@RequestParam String token) {
        Map<String, Object> info = new HashMap<>();
        HOSUser user = cacheComponent.getObj(RedisCachePreFix.USERINFO.getCachePreFix() + token, HOSUser.class);

        String localToken = cacheComponent.getRaw(RedisCachePreFix.USERTOKEN.getCachePreFix() + user.getId());


        info.put("user", user);
        info.put("localToken", localToken);
        info.put("token", token);
        info.put("isEqual", token.equals(localToken));

        return ResponseUtil.ok(info);
    }

    @PostMapping("/testPdfData")
    @ApiOperation(value = "pdf本地数据测试")
    public Object testPdfData(@RequestParam @ApiParam("问卷ID") Integer paperId) {
        try {
            /**
             ClassPathResource resource = new ClassPathResource("data/test.json");
             byte[] bytes = FileCopyUtils.copyToByteArray(resource.getInputStream());
             String str = new String(bytes, StandardCharsets.UTF_8);**/

            return wxPaperPdfService.createPdfByPaperId(paperId);
        } catch (Exception e) {
            log.error(e.toString());
        }

        return ResponseUtil.fail();


    }


    @PostMapping("/testPdfCreate")
    @ApiOperation(value = "pdf生成")
    public Object testPdfCreate(@RequestBody JSONObject data) {
        try {

            AIPdfResDto resDto = pdfAiApiService.createPdf(data);
            return ResponseUtil.ok(resDto);
        } catch (Exception e) {
            log.error(e.toString());
        }

        return ResponseUtil.fail();


    }


    @PostMapping("/testPdfUrl")
    @ApiOperation(value = "pdf转存到腾讯云")
    public Object testPdfCreate(@RequestParam String pdfUrl) {
        try {

            try {
                URI uri = new URI(pdfUrl);
                URL obj = uri.toURL();
                HttpURLConnection conn = (HttpURLConnection) obj.openConnection();
                conn.setReadTimeout(60_000);// 30秒读取超时
                conn.setConnectTimeout(10_000); // 10秒连接超时

                // 先获取内容长度（可能不可用）
                long contentLength = conn.getContentLengthLong();
                System.out.println("Content-Length: " + contentLength + " bytes");


                HOSStorage storage = storageService.store(conn.getInputStream(), contentLength, "image/pdf", "haopy_check_report_" + "66666" + ".pdf");
                System.out.println(storage.getUrl());
                Map<String, Object> data = new HashMap<>();
                data.put("url", storage.getUrl());
                return ResponseUtil.ok(data);


            } catch (Exception e) {
                log.error("读物体检报告失败，错误：" + e.getMessage());
                e.printStackTrace();
            }
        } catch (Exception e) {
            log.error(e.toString());
        }

        return ResponseUtil.fail();


    }


    @PostMapping("/preIllnessByPaperId")
    @ApiOperation(value = "预测可能出现的疾病")
    public Object preIllnessByPaperId(@RequestParam Integer userId) throws Exception {

        return wxPapersPresIllnessService.createPaperByPreIllnessPdfJson(userId, null);
    }


    @PostMapping("/preDrugs")
    @ApiOperation(value = "推荐用药")
    public Object preDrugs(@RequestParam String userId, @RequestParam String input, @RequestParam String query) throws Exception {
        Map<String, Object> params = new HashMap<>();
        params.put("input", input);
        return chatAiApiService.chatMessage(userId, "", params, query, chatApiProperties.getPreDrugsKey());
    }

    @PostMapping("/preDrugsByPaperId")
    @ApiOperation(value = "推荐用药")
    public Object preDrugsByPaperId(@RequestParam Integer paperId) throws Exception {
        wxPapersDrugsService.recommendDrugsByPaperId(paperId);
        return ResponseUtil.ok();
    }

    @PostMapping("/paperSummary")
    @ApiOperation(value = "总结")
    public Object paperSummary(@RequestParam Integer paperId) throws Exception {
        paperIllnessToAISyncService.syncPaperSummary(paperId);
        return ResponseUtil.ok();
    }

}